package com.baidu.structure.fragments;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import com.baidu.structure.R;
import com.baidu.structure.activity.ChatActivity;
import com.baidu.structure.adapter.ContactAdapter;
import com.baidu.structure.bean.ContactBean;
import com.baidu.structure.bean.ContactGroupBean;
import com.baidu.structure.constants.Tags;
import com.baidu.structure.utils.ConfigUtils;
import com.baidu.structure.utils.JumpUtils;
import com.baidu.structure.utils.ThreadPoolUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.exceptions.HyphenateException;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContactFragment extends Fragment implements ExpandableListView.OnChildClickListener {
    private ExpandableListView menuList;
    private ArrayList<ContactGroupBean> menuData;
    private ContactAdapter adapter;

    private Handler handler;
    public static final int SUCCESS = 51;

    private EventBus bus;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_contact, container, false);
        init(v);
        return v;
    }

    private void init(View v) {
        bus = EventBus.getDefault();
        bus.register(getActivity());
        menuList = (ExpandableListView) v.findViewById(R.id.menuList);
        menuData = new ArrayList<>();
        menuData.add(new ContactGroupBean("聊天群", new ArrayList<ContactBean>()));
        menuData.add(new ContactGroupBean("联系人", new ArrayList<ContactBean>()));
        menuData.add(new ContactGroupBean("黑名单", new ArrayList<ContactBean>()));
        adapter = new ContactAdapter(menuData, getActivity());
        menuList.setAdapter(adapter);
        menuList.setOnChildClickListener(this);


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case SUCCESS:
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        };
    }

    private void loadingData() {
        menuData.get(0).getChildList().clear();
        menuData.get(1).getChildList().clear();
        menuData.get(2).getChildList().clear();
        ThreadPoolUtils.execute(new TimerTask() {
            @Override
            public void run() {
                try {
                    List<String> contacts = EMClient.getInstance().contactManager().getAllContactsFromServer();
                    if (contacts != null) {
                        for (String con : contacts) {
                            menuData.get(1).getChildList().add(new ContactBean(R.mipmap.back, con));
                        }
                    }

                    List<EMGroup> groups = EMClient.getInstance().groupManager().getJoinedGroupsFromServer();
                    if (groups != null) {
                        for (EMGroup r : groups) {
                            menuData.get(0).getChildList().add(new ContactBean(R.mipmap.naruto, r.getGroupName()));
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(SUCCESS);
            }
        });

    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        Intent intent = new Intent(getActivity(), ChatActivity.class);
        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        intent.putExtra(EaseConstant.EXTRA_USER_ID, menuData.get(groupPosition).getChildList().get(childPosition).getName());
        JumpUtils.simpleJump(getActivity(), intent);
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (EMClient.getInstance().isLoggedInBefore())
            loadingData();
    }

    @Override
    public void onDestroy() {
        bus.unregister(getActivity());
        super.onDestroy();
    }

    @Subscriber(tag = Tags.CONTACT)
    public void updateContacts(int tag) {
        switch (tag) {
            case SUCCESS:
                loadingData();
                break;
        }
    }
}
